package com.omybug.test.swagger.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * @author: omybug
 * @date: 2019/2/28 11:21
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${swagger.open}")
    private boolean swaggerOpen;

    @Bean
    public Docket createRestApi() {
        List<Parameter> pars = new ArrayList<Parameter>();
        // 添加公共参数
        ParameterBuilder tokenParameter = new ParameterBuilder();
        tokenParameter.name("Authorization").description("令牌")
                .modelRef(new ModelRef("string")).parameterType("header").required(true).defaultValue("xxxxxxx");
        pars.add(tokenParameter.build());
        Set<String> consumes = new HashSet<String>();
        consumes.add(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        Set<String> produces = new HashSet<String>();
        produces.add(MediaType.APPLICATION_JSON_UTF8_VALUE);
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(this.swaggerOpen)
                .apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.basePackage("com.omybug.test.swagger"))
                .paths(PathSelectors.any())
                .build().globalOperationParameters(pars)
                .consumes(consumes).produces(produces);
//                .pathMapping("/doc/v1.0");
    }

    @SuppressWarnings("deprecation")
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("个人测试")
//                .description("个人测试用api")
//                .termsOfServiceUrl("https://www.omybug.com")
//                .description("测试描述")
                .version("1.0")
                .build();
    }

}
